package frame.PayMain;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.EmployeeMapper;
import org.example.mapper.PayMainMapper;
import org.example.pojo.Employee;
import org.example.pojo.PayMain;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.List;

public class PayMainUpdate extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private PayMainMapper payMainMapper = sqlSession.getMapper(PayMainMapper.class);
    private EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
    private JComboBox<String> eidComboBox;


    public PayMainUpdate() {
        // 设置内部窗口的标题和关闭方式
        setTitle("修改采购信息");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);

        // 添加表头
        String[] columnNames = {"采购编号", "员工编号", "采购数量", "采购总价", "采购时间", "备注"};
        tableModel.setColumnIdentifiers(columnNames);

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 初始化员工编号下拉框
        eidComboBox = new JComboBox<>();
        populateEidComboBox();

        // 将员工编号下拉框添加到表格的员工编号列
        TableColumn eidColumn = table.getColumnModel().getColumn(1); // 1 是员工编号列的索引
        eidColumn.setCellEditor(new DefaultCellEditor(eidComboBox));

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel();
        JButton updateButton = new JButton("确定修改");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updatePayMain(); // 点击确定修改按钮时执行更新操作
            }
        });
        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new PayMainPanel());
            }
        });
        buttonPanel.add(updateButton);
        buttonPanel.add(returnButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 初始化表格数据
    private void initializeTableData() {
        List<PayMain> payMains = payMainMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (PayMain payMain : payMains) {
            tableModel.addRow(new Object[]{
                    payMain.getPid(),
                    payMain.getEid(),
                    payMain.getPcount(),
                    payMain.getPtotal(),
                    payMain.getPdate(),
                    payMain.getOther()
            });
        }
    }

    // 更新采购信息到数据库
    private void updatePayMain() {
        int rowCount = table.getRowCount();
        boolean hasChanges = false; // 检查是否有任何数据变化

        for (int row = 0; row < rowCount; row++) {
            Integer pid = null;
            try {
                pid = Integer.parseInt(table.getValueAt(row, 0).toString().trim());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "采购编号字段必须是整数！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String eid = table.getValueAt(row, 1).toString().trim();

            Integer pcount = null;
            try {
                pcount = Integer.parseInt(table.getValueAt(row, 2).toString().trim());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "采购数量字段必须是整数！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            float ptotal = 0.0f;
            try {
                ptotal = Float.parseFloat(table.getValueAt(row, 3).toString().trim());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "采购总价字段必须是浮点数！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String pdate = table.getValueAt(row, 4).toString().trim();
            String other = table.getValueAt(row, 5).toString().trim();

            // 检查关键字段不能为空字符
            if (eid.isEmpty() || ptotal == 0.0f || pdate.isEmpty()) {
                JOptionPane.showMessageDialog(this, "每一行的员工编号、采购数量、采购总价、采购时间都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 获取原始数据
            PayMain originalPayMain = payMainMapper.queryPayMainById(pid);
            if (originalPayMain != null) {
                // 检查数据是否有变化
                if (!originalPayMain.getEid().equals(eid)
                        || !originalPayMain.getPcount().equals(pcount)
                        || originalPayMain.getPtotal() != ptotal
                        || !originalPayMain.getPdate().equals(pdate)
                        || !originalPayMain.getOther().equals(other)) {
                    // 更新数据库中的采购信息
                    PayMain updatedPayMain = new PayMain(eid, pcount, ptotal, pdate, other);
                    updatedPayMain.setPid(pid); // 更新时需要设置 pid
                    payMainMapper.updatePayMain(updatedPayMain);
                    hasChanges = true; // 标记有变化
                }
            }
        }

        if (hasChanges) {
            JOptionPane.showMessageDialog(this, "采购信息已更新！", "提示", JOptionPane.INFORMATION_MESSAGE);
            // 刷新表格数据
            refreshTableData();
        } else {
            JOptionPane.showMessageDialog(this, "没有检测到任何更改。", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // 刷新表格数据的方法
    private void refreshTableData() {
        List<PayMain> payMains = payMainMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (PayMain payMain : payMains) {
            tableModel.addRow(new Object[]{
                    payMain.getPid(),
                    payMain.getEid(),
                    payMain.getPcount(),
                    payMain.getPtotal(),
                    payMain.getPdate(),
                    payMain.getOther()
            });
        }
    }

    // 填充员工编号下拉框
    private void populateEidComboBox() {
        List<Employee> employees = employeeMapper.selectAll();
        for (Employee employee : employees) {
            eidComboBox.addItem(employee.getEid());
        }
    }
}
